import { Inject, Service } from "typedi";
import { isEmpty } from "lodash-unified";
import { esi } from "../index";
import { AuthService } from "../AuthService";
import { Role } from "../role/entity";
import { PlayerPlanet } from "./entity/PlayerPlanet";
import type { PlanetRoute } from "@scvzerng/esi-163/dist/types/esi/plants/model/PlanetLayout";

const getRouteId = (route: PlanetRoute) => {
  return `${route.content_type_id}_${route.source_pin_id}_${route.destination_pin_id}`;
};

@Service()
export class PlanetService {
  @Inject(() => AuthService)
  private authService!: AuthService;
  async getPlanets(playerIds?: number[]) {
    const roles = await this.authService.getAuthRoles();
    const playerPlanets: Role[] = [];
    for (const role of roles) {
      if (!isEmpty(playerIds) && !playerIds?.includes(role.id)) {
        continue;
      }
      const user = new Role(role);
      const token = await this.authService.getAccessToken(role);
      const planets = await esi.plant.list(role.id, token);
      const formatPlants = [];
      for (const planet of planets ?? []) {
        const layout = await esi.plant.layout(role.id, planet.planet_id, token);
        if (layout) {
          //有bug 会有重复的route出现虽然route_id不一样需要进行过滤 使用${content_type_id}_${source_pin_id}_${destination_pin_id}确定唯一性
          const routeIds = new Set();
          layout.routes = layout.routes.filter((route) => {
            if (routeIds.has(getRouteId(route))) {
              return false;
            }
            routeIds.add(getRouteId(route));
            return true;
          });
          formatPlants.push(PlayerPlanet.from(planet, layout!, role.name));
        }
      }
      user.planets = formatPlants;
      playerPlanets.push(user);
    }

    return playerPlanets;
  }
}
